package com.lbz.utils;

import java.math.BigDecimal;

/**
 * 解决购物车中计算商品价格时丢失计算精度的问题，在affective java书中提到，float、double这些精度计算
 * 只能用在科研领域能忽略小精度问题的方面，在商业计算一定要用BigDecimal.
 *
 * @Author 林必昭
 * @Date 2019/6/18 16:15
 */
public class BigDecimalUtil {

    public BigDecimalUtil() {
    }

    public static BigDecimal add(double v1, double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2);
    }

    public static BigDecimal sub(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2);
    }

    public static BigDecimal mul(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2);
    }

    public static BigDecimal div(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);    //四舍五入，保留2位小数
    }
}
